import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_shensu/common/model/game.dart';
import 'package:flutter_shensu/common/util/navigator_utils.dart';
import 'package:flutter_shensu/common/util/network_utils.dart';
import 'package:fluttertoast/fluttertoast.dart';

class IOSGamePageState extends State<StatefulWidget>
    with AutomaticKeepAliveClientMixin {
  List<Game> _gameList = [];

  @override
  void initState() {
    super.initState();
    getAllGameList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: _getBody(),
    );
  }

  void getAllGameList() async {
    List<Game> future = await NetWorkUtils.instance.getAllGameList();
    setState(() {
      _gameList = future;
    });
  }

  Widget _getBody() {
    if (_gameList.length != 0) {
      return new GridView.count(
        padding: EdgeInsets.fromLTRB(10, 30, 10, 10),
        crossAxisCount: 4,
        childAspectRatio: 15 / 18,
        primary: false,
        children: _gameList.map((Game g) {
          return _getGameItemWidget(context, g);
        }).toList(),
      );
    } else {
      return Center(
        child: CupertinoActivityIndicator(),
      );
    }
  }

  Widget _getGameItemWidget(BuildContext context, Game g) {
    return new Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        GestureDetector(
          onTap: () {
            NavigatorUtils.goISpeedPage(context, g);
          },
          child: Container(
            width: 60.0,
            height: 60.0,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(
              Radius.circular(15.0),
            )),
            child: CachedNetworkImage(
              imageUrl: g.game_icon_url,
              placeholder: new CircularProgressIndicator(
                strokeWidth: 2.0,
              ),
              errorWidget: new Icon(Icons.error),
            ),
          ),
        ),
        Padding(
          padding: new EdgeInsets.fromLTRB(0, 8, 0, 0),
        ),
        SizedBox(
          width: 80,
          child: Text(
            g.game_name_zh,
            textAlign: TextAlign.center,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(fontSize: 14.0, color: Colors.black),
          ),
        )
      ],
    );
  }

  void _showToast(var message) {
    Fluttertoast.showToast(
        msg: message, toastLength: Toast.LENGTH_SHORT, timeInSecForIos: 1);
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
